#!/usr/bin/python

__author__ = 'mbieliau gmail.com (Marius Bieliauskas)'

import re
import cgi
import random
import logging

from google.appengine.ext import db
from google.appengine.api import users
from google.appengine.ext import webapp
from google.appengine.ext.webapp.util import run_wsgi_app

from waveapi import model
from waveapi import robot
from waveapi import events

class Censor(db.Model):
  author = db.UserProperty()
  word = db.StringProperty()
  date = db.DateTimeProperty(auto_now_add=True)


def OnRobotAdded(properties, context):
  """Invoked when the robot has been added."""
  notify(context, "Hello, I'm a censor, please try not to curse! " + 
                  "Also never write something like this: " + 
                  "curse:paper or uncurse:ass" +
                  "Source code: http://code.google.com/p/censorshiprobot")


def OnBlipSubmitted(properties, context):
  """Invoked when the blip has been added."""
  blip = context.GetBlipById(properties['blipId'])
  contents = blip.GetDocument().GetText()

  update_dictionary(contents)
   
  new_contents = replace_contents(contents)
  
  if contents != new_contents:
    """Prevent from unnessasary update"""
    blip.GetDocument().SetText(new_contents)


def OnDocumentChanged(properties, context):
  """Invoked when the document has been changed."""
  blip = context.GetBlipById(properties['blipId'])
"""
  contents = blip.GetDocument().GetText()

  new_contents = replace_contents(contents)
  
  if contents != new_contents:
      opDocument = OpBasedDocument(blip.GetDocument())
  opDocument.InsertText(0, '+')
  blip.GetDocument().SetText(new_contents)
"""


def update_dictionary(text):
  censor = re.findall('(?<=censor\:)\w+',text)
  uncensor = re.findall('(?<=uncensor\:)\w+',text)
    
  for word in censor:
    add_word(word)
        
  for word in uncensor:
    remove_word(word)

def add_word(word):
  censor = Censor()

  if users.get_current_user():
    censor.author = users.get_current_user()

  censor.word = word
  censor.put()

    
def remove_word(word):
  q = db.GqlQuery("SELECT __key__ FROM Censor WHERE word = :1", word)
  results = q.fetch(10)
  db.delete(results)
    

def notify(context, message = 'empty'):
  root_wavelet = context.GetRootWavelet()
  root_wavelet.CreateBlip().GetDocument().SetText(message)


def repl(word):
  inner_word = list(word)

  if len(inner_word) < 1:
    return word

  result = inner_word[0]

  for index in range(1,len(inner_word)):
    #result = result + random.choice(['%','@','#','$','&','*'])
    result = result + random.choice(['*','*','*'])

  return result


def replace_contents(text):
  results = db.GqlQuery("SELECT * FROM Censor")
    
  new_text = text
    
  for result in results:

    new_text = re.sub(result.word, repl(result.word), new_text)        
  return new_text



if __name__ == '__main__':
  myRobot = robot.Robot('censorshiprobot',
      image_url='http://censorshiprobot.appspot.com/icon.jpg',
      version='19',
      profile_url='http://censorshiprobot.appspot.com/')

  myRobot.RegisterHandler(events.WAVELET_SELF_ADDED, OnRobotAdded)
  myRobot.RegisterHandler(events.BLIP_SUBMITTED, OnBlipSubmitted)
  myRobot.RegisterHandler(events.DOCUMENT_CHANGED, OnDocumentChanged)

  myRobot.Run()

